package com.mgface.zookeeper.curator.function;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * 监听当前节点的变化
 * 
 * @author user
 *
 */
public class 当前节点事件监听 {
	public static void main(String[] args) throws Exception {
		CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181")
				.sessionTimeoutMs(10_000).connectionTimeoutMs(10_000).retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.build();
		client.start();
		System.out.println("连接启动完毕");
		String path = "/event";
		client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "init".getBytes());
		final NodeCache cache = new NodeCache(client, path, false);
		cache.start(true);// nodecache在第一次启动的时候立刻从zk读取对应数据节点的内容，保存在cache里面
		cache.getListenable().addListener(() -> {
			System.out.println(Thread.currentThread().getName());
			ChildData childData = cache.getCurrentData();
			if (childData == null) {
				System.out.println("===delete, path=" + path + ", childData=" + childData);
			} else {
				System.out.println("===update or add, path=" + path + ", childData="
						+ new String(childData.getData(), StandardCharsets.UTF_8));
			}
		}, Executors.newFixedThreadPool(4));
		client.setData().forPath(path, "init2".getBytes());
		TimeUnit.SECONDS.sleep(1);
		client.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
		TimeUnit.SECONDS.sleep(5);
		cache.close();
	}

}
